<template>
  <div
      id="iframe-origin"
      class="iframe"
  >
    <div id="map-container" :style="{ visibility: type.startsWith('map') ? 'visible' : 'hidden' }" class="map"/>
    <div v-if="type === 'camera'" class="imgList">
      <template v-for="(item,index) in cameraPoint">
        <img
             :style="{
        top:item.top,
        left:item.left
           }"
             alt="1"
             class="sxt" src="~@/assets/base-image-camera.png" @click="onPreviewVideo(item)"
        >
<!--        {{ index }}-->
      </template>
    </div>
    <preview v-if="showPreview" :url="previewUrl" type="video" @close="showPreview = false"/>
    <DialogCamera v-if="showCamera" :url="CameraUrl" @close="showCamera = false"/>

  </div>
</template>
<!--<script type="text/javascript" src="https://webapi.amap.com/maps?v=2.0&key=b5cc346dad2e1078dc72c083fafb2d3e&plugin=AMap.MoveAnimation"></script>-->

<script setup>
import {onMounted, ref, shallowRef, watch} from "vue";

import Preview from "@/components/customs/preview/index.vue";
import {inject} from "@vue/runtime-core";
import {CameraList, RouteFk, RouteList, RouteMsr} from "@/common/customs/security";
import cameraIcon from "@/assets/base-image-camera.png";
import houseIcon from "@/assets/base-image-house.png";
import doorIcon from "@/assets/base-image-door.png";
import deviceIcon from "@/assets/base-image-device.png";
import {AttendLou} from "@/pages/attend/data";
import {SqlApi} from "@/common/customs/overview";
import DialogCamera from "@/components/customs/dialog-camera/index.vue";

// eslint-disable-next-line no-undef
const props = defineProps({
  type: {
    type: String,
    default: "static",
  },
});

const showPreview = ref(false);
const previewUrl = ref("");
let AMap = null;
let mapInstance = shallowRef(null);
let markers = [];
let routes = [];
const center = [120.631946, 27.983144];
const CameraUrl = ref("");
const showCamera = ref(false);
const cameraPoint = [
  {
    code: "7d225ee865a946859d174716cd6e75eb",
    left: "30%",
    top: "44%",
  },
  {
    code: "e13a8aad5b2048f99789bccc9ef564fe",
    left: "53%",
    top: "21%",
  },
  {
    code: "29c13adae29b4de0b9560a8370b088d5",
    left: "41%",
    top: "58%",
  },
  {
    code: "7d225ee865a946859d174716cd6e75eb",
    left: "56%",
    top: "38%",
  },
  {
    code: "a9518215a9834a44b18aa5b6b28c70f9",
    left: "56%",
    top: "68%",
  },
  {
    code: "347a48ecdeee4d128bd482dae46c0b0e",
    left: "67%",
    top: "56%",
  },
  {
    code: "0f7a930899a5496d9c4bea9097fcb2c5",
    left: "62%",
    top: "30%",
  },
  {
    code: "b12ecb02d9f74466bab2ef93f5fbf271",
    left: "66%",
    top: "36%",
  },
];
const doorPoint = [
  [120.632088, 27.981021],
  [120.633474, 27.983158],
  [120.632272, 27.985764],
];
const devicePoint = [
  [120.632701, 27.982853],
  [120.632744, 27.982411],
  [120.632779, 27.981966],
  [120.631407, 27.981875],
  [120.631325, 27.982676],
  [120.632192, 27.983307],
];
const routePoint = [
  [120.631826, 27.981588],
  [120.632307, 27.98164],
  [120.632321, 27.981918],
  [120.632258, 27.982826],
  [120.631674, 27.982826],
  [120.631389, 27.983074],
  [120.631345, 27.983479],
  [120.632476, 27.983491],
].reverse();

const housePoint = [
  {
    name: 1,
    point: [120.632782, 27.98484],
  },
  {
    name: 2,
    point: [120.632859, 27.984479],
  },
  {
    name: 3,
    point: [120.632824, 27.984165],
  },
  {
    name: 5,
    point: [120.632094, 27.983803],
  },
  {
    name: 6,
    point: [120.632024, 27.984067],
  },
  {
    name: 7,
    point: [120.632036, 27.984294],
  },
  {
    name: 8,
    point: [120.632096, 27.984753],
  },
  {
    name: 9,
    point: [120.632085, 27.985122],
  },
  {
    name: 10,
    point: [120.631452, 27.985139],
  },
  {
    name: 11,
    point: [120.631467, 27.984647],
  },
  {
    name: 12,
    point: [120.631513, 27.984333],
  },
  {
    name: 13,
    point: [120.630867, 27.984726],
  },
  {
    name: 14,
    point: [120.630858, 27.985145],
  },
  {
    name: 15,
    point: [120.63081, 27.985464],
  },
  {
    name: 16,
    point: [120.631584, 27.985485],
  },
  {
    name: 17,
    point: [120.632079, 27.985529],
  },
];
const isLoading = inject("isLoading");
const smartObject = inject("smartObject");
const onPageChange = inject("pageChange");
const initComplete = ref(false);

const onPreviewVideo = async (item) => {
  isLoading.value = true;
  try {
    const api = new SqlApi().params({
      cameraIndexCode: item.code,
    });
    await api.send();
    const data = await api.getDatas();
    console.log(data);
    CameraUrl.value = data.data;
    showCamera.value = true;
    isLoading.value = false;
  } catch (e) {
    console.log(e);
    isLoading.value = false;
  }
};

const initMap = () => {
  console.log("init map", AMap, mapInstance.value);
  mapInstance.value = new AMap.Map("map-container", {
    viewMode: "3D",
    pitch: 45,
    rotation: -45,
    zooms: [3, 20],
    expandZoomRange: true,
    pitchEnable: false,
    rotateEnable: false,
    zoom: 18,
    center,
  });
  mapInstance.value.on("click", (event) => {
    console.log(`${event.lnglat.getLng()}, ${event.lnglat.getLat()}`);
  });

  // var styleName = "amap://styles/fresh";
  // mapInstance.value.setMapStyle(styleName);
};

const houseMarkerClick = (name) => {
  smartObject.ssl = name.id;
  smartObject.sslObj = name;
  onPageChange(31);
};

const addHouse = async () => {
  // mapInstance.value.setCenter([120.631719, 27.984902]);
  mapInstance.value.setZoomAndCenter(19, [120.631719, 27.984902]);
  smartObject.ssl = "";
  const api = new AttendLou();
  await api.send();
  const {data} = await api.getDatas();
  const icon = new AMap.Icon({
    size: new AMap.Size(50, 50),
    image: cameraIcon,
    imageOffset: new AMap.Pixel(0, 0),
    imageSize: new AMap.Size(50, 50),
  });
  housePoint.forEach((point) => {
    const dataKey = data.find(item => item.name === point.name);
    if (dataKey !== undefined) {
      point.id = dataKey.id;
    }
    let markerContent = "" +
        "<div class=\"custom-content-marker\">" +
        "   <img src=" + houseIcon + ">" +
        "   <div class=\"infoText\">" + point.name + "号宿舍楼</div>" +
        "</div>";

    const marker = new AMap.Marker({
      position: new AMap.LngLat(...point.point),
      offset: new AMap.Pixel(-50, -60),
      content: markerContent,
    });
    marker.on("click", () => {
      houseMarkerClick(point);
      // onPreviewVideo("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
    });
    markers.push(marker);
    mapInstance.value.add(markers);
  });
};

const addCamera = async () => {
  const api = new CameraList();
  api.params({
    page: 1,
    page_size: 999,
  });
  await api.send();
  const {data} = await api.getDatas();

  mapInstance.value.setZoom(18);
  const icon = new AMap.Icon({
    size: new AMap.Size(20, 20),
    image: cameraIcon,
    imageOffset: new AMap.Pixel(0, 0),
    imageSize: new AMap.Size(20, 20),
  });
  // cameraPoint.forEach((point) => {
  if (data.length && data.data.length) {
    data.data.forEach((point) => {
      const marker = new AMap.Marker({
        position: new AMap.LngLat(point.jd, point.wd),
        offset: new AMap.Pixel(-25, -25),
        icon,
      });
      // marker.on("click", () => {
      //   onPreviewVideo("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
      // });
      markers.push(marker);
      mapInstance.value.add(markers);
    });
  }

};

const addDoor = () => {
  mapInstance.value.setZoom(18);
  const icon = new AMap.Icon({
    size: new AMap.Size(50, 50),
    image: doorIcon,
    imageOffset: new AMap.Pixel(0, 0),
    imageSize: new AMap.Size(50, 50),
  });
  doorPoint.forEach((point) => {
    const marker = new AMap.Marker({
      position: new AMap.LngLat(...point),
      offset: new AMap.Pixel(-25, -25),
      icon,
    });
    // marker.on("click", () => {
    //   onPreviewVideo("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
    // });
    markers.push(marker);
    mapInstance.value.add(markers);
  });
};

const addDevice = () => {
  mapInstance.value.setZoom(18);

  const icon = new AMap.Icon({
    size: new AMap.Size(50, 50),
    image: deviceIcon,
    imageOffset: new AMap.Pixel(0, 0),
    imageSize: new AMap.Size(50, 50),
  });
  devicePoint.forEach((point) => {
    const marker = new AMap.Marker({
      position: new AMap.LngLat(...point),
      offset: new AMap.Pixel(-25, -25),
      icon,
    });
    // marker.on("click", () => {
    //   onPreviewVideo("http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4");
    // });
    markers.push(marker);
    mapInstance.value.add(markers);
  });
};

const addRoute = async () => {
  mapInstance.value.setZoom(17);
  smartObject.list = [];
  if (!smartObject.xh) {
    return;
  }
  isLoading.value = true;
  try {
    const api = new RouteList();
    api.params({
      // page: 1,
      // page_size: 20,
      XH: smartObject.xh,
      sj: smartObject.sj || undefined
    });
    await api.send();
    const {data} = await api.getDatas();
    isLoading.value = false;
    if (data.length === 0) {
      return;
    }
    let arr = [];
    // let listData = [];
    // for (const listDatum in data.data) {
    //   let i = data.data[listDatum];
    //   if (i.jd && i.wd) {
    //     arr.push([Number(i.jd), Number(i.wd)]);
    //   }
    //   listData.push({
    //     title: i.cameraName,
    //     info2: i.cameraName,
    //     date: i.faceTime,
    //     image: i.bkgUrl,
    //   });
    // }
    arr = data.filter(item => {
      return item.jd && item.wd;
    }).map(i => {
      return [Number(i.jd), Number(i.wd)];
    });
    smartObject.sj = "";
    smartObject.list = data.map((i, index) => {
      return {
        title: `画面${index + 1}`,
        info2: i.cameraName,
        date: i.faceTime,
        image: i.bkgUrl || "https://img0.baidu.com/it/u=1364083773,2034341024&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=285",
      };
    });
    arr.forEach((item, index) => {
      const content = `<div class="marker-route marker-marker-bus-from">${index + 1}</div>`;

      let marker = new AMap.Marker({
        content,
        map: mapInstance.value,
        position: item,
        // icon: "#",
        offset: new AMap.Pixel(-15, -15),
      });
      markers.push(marker);
    });
    AMap.plugin("AMap.MoveAnimation", function () {
      const route = new AMap.Polyline({
        map: mapInstance.value,
        strokeColor: "#ffff00",
        strokeWeight: 6,
        strokeOpacity: 1,
      });
      const marker = new AMap.Marker({
        map: mapInstance.value,
        position: arr[0],
        icon: "#",
        offset: new AMap.Pixel(0, 0),
      });
      markers.push(marker);
      routes.push(route);
      marker.on("moving", function (event) {
        route.setPath(event.passedPath);
        mapInstance.value.setCenter(event.target.getPosition(), true);
      });
      // mapInstance.value.setFitView();
      marker.moveAlong(arr, {
        duration: 1000,
      });
    });
  } catch (e) {
    console.log(e);
    isLoading.value = false;
  }
};

const msrRoute = async () => {
  mapInstance.value.setZoom(19);
  smartObject.msrList = [];
  console.log(smartObject);
  if (!smartObject.msr) {
    return;
  }
  isLoading.value = true;
  try {
    let api;
    if (smartObject.isFk) {
      api = new RouteFk();
      api.params({
        visitorId: smartObject.msr,
      });
    } else {
      api = new RouteMsr();
      api.params({
        msr_id: smartObject.msr,
      });
    }
    smartObject.isFk = false;
    await api.send();
    const {data} = await api.getDatas();
    isLoading.value = false;
    let arr = [];
    arr = data.data.filter(item => {
      return item.jd && item.wd;
    }).map(i => {
      return [Number(i.jd), Number(i.wd)];
    });
    // data.data.map(i => {
    let newData = data.data.sort((a, b) => {
      let timeA = new Date(a.sj);
      let timeB = new Date(b.sj);
      return timeA - timeB;
    }).map((i, index) => {
      return {
        title: `画面${index + 1}`,
        info2: i.cameraName,
        date: i.sj,
        image: i.facePicUrl,
        type: i.type,
        cameraIndexCode: i.cameraIndexCode,
      };
    });
    let typeIndex = newData.findIndex(i => {
      return i.type === 1;
    });
    if (typeIndex !== -1) {
      let prev = newData[typeIndex - 1];
      let item = newData[typeIndex];
      let next = newData[typeIndex + 1];
      if (prev) {
        prev.cameraIndexCode === item.cameraIndexCode ? newData[typeIndex - 1] = "" : "";
      }
      if (next) {
        next.cameraIndexCode === item.cameraIndexCode ? newData[typeIndex + 1] = "" : "";
      }
    }
    smartObject.msrList = newData.filter(item => {
      return item;
    });
    arr.forEach((item, index) => {
      const content = `<div class="marker-route marker-marker-bus-from">${index + 1}</div>`;

      let marker = new AMap.Marker({
        content,
        map: mapInstance.value,
        position: item,
        // icon: "#",
        offset: new AMap.Pixel(-15, -15),
      });
      markers.push(marker);
    });
    AMap.plugin("AMap.MoveAnimation", function () {
      const route = new AMap.Polyline({
        map: mapInstance.value,
        strokeColor: "#ffff00",
        strokeWeight: 6,
        strokeOpacity: 1,
      });
      const marker = new AMap.Marker({
        map: mapInstance.value,
        position: arr[0],
        icon: "#",
        offset: new AMap.Pixel(0, 0),
      });
      markers.push(marker);
      routes.push(route);

      marker.on("moving", function (event) {
        route.setPath(event.passedPath);
        mapInstance.value.setCenter(event.target.getPosition(), true);
      });
      // mapInstance.value.setFitView();
      marker.moveAlong(arr, {
        duration: 1000,
      });
    });
  } catch (e) {
    isLoading.value = false;
    smartObject.isFk = false;
  }
};

const refresh = () => {
  if (initComplete.value) {
    props.type === "map-house" ? mapInstance.value.setCenter([120.631784, 27.984519]) :
        mapInstance.value.setCenter(center);
    if (props.type === "map-camera") {
      addCamera();
    } else if (props.type === "map-door") {
      addDoor();
    } else if (props.type === "map-house") {
      addHouse();
    } else if (props.type === "map-guest") {
      msrRoute();
    } else if (props.type === "map-device") {
      addDevice();
    } else if (props.type === "map-route") {
      addRoute();
    }
  }
};

const closeMap = () => {
  markers.forEach((marker) => {
    marker?.stopMove();
    mapInstance.value.remove(marker);
  });
  routes.forEach((route) => mapInstance.value.remove(route));
  markers = [];
  routes = [];
  refresh();
};
// eslint-disable-next-line no-undef
defineExpose({
  refresh, closeMap
});

onMounted(() => {
  // AMap = window.AMap;
  // initMap();
  // initComplete.value = true;
  // refresh();
  // const scriptEl = document.createElement("script");
  // scriptEl.src = "";
  // document.body.appendChild(scriptEl);
  // scriptEl.onload = () => {
  //   AMap = window.AMap;
  //   initMap();
  //   setTimeout(() => {
  //     initComplete.value = true;
  //     refresh();
  //   }, 4000);
  // };
});

watch(() => props.type, () => {
  markers.forEach((marker) => {
    marker?.stopMove();
    mapInstance.value.remove(marker);
  });
  routes.forEach((route) => mapInstance.value.remove(route));
  markers = [];
  routes = [];
  console.log("watch", props.type);
  refresh();
});
</script>

<style lang="less" scoped>
@import "./index.less";

:deep(.custom-content-marker) {
  position: relative;
  //width: 25px;
  //height: 34px;

  //img {
  //  width: 100%;
  //  height: 100%;
  //}

  .infoText {
    position: absolute;
    left: 0;
    top: 12px;
    width: 100%;
    text-align: center;
  }
}
</style>
